package com.asura.app.wechat.base.mvp;


import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;


/**
 * Created by Asura on 2016/8/2.
 */
public abstract class BasePresenter<V extends Mvp.View> implements Mvp.Presenter<V> {

    private V mMvpView;
    protected CompositeDisposable compositeDisposable;


    protected V getMvpView() {
        return mMvpView;
    }

    protected void checkViewAttached() {
        if (!isViewAttached()) throw new MvpViewNotAttachedException();
    }

    @Override
    public boolean isViewAttached() {
        return mMvpView != null;
    }


    @Override
    public void attachView(V v) {
        mMvpView = v;
    }

    @Override
    public void detachView() {
        mMvpView = null;
        if (compositeDisposable != null && !compositeDisposable.isDisposed()) {
            compositeDisposable.clear();
        }
        compositeDisposable = null;
    }


    protected void addSubscription(Disposable disposable) {
        if (compositeDisposable == null) {
            compositeDisposable = new CompositeDisposable();
        }
        compositeDisposable.add(disposable);
    }

    protected void cancelAllSubscriptions() {
        if (compositeDisposable != null) {
            compositeDisposable.clear();
        }
    }
}
